<template>
  <com-page class="home-page">
    <u-navbar placeholder
              leftIcon=""
              :title="currentEventName || $t('tabbar.home')" />

    <!-- 顶部横幅 + 倒计时卡片 -->
    <view class="banner-wrapper com-mb-sm">
      <swiper class="banner-swiper" 
              circular 
              indicator-dots 
              :autoplay="false"
              indicator-color="rgba(255,255,255,0.3)"
              indicator-active-color="#fff"
              @change="onSwiperChange">
        <swiper-item v-for="event in eventList" 
                     :key="event.id">
          <image class="banner-image"
                 :src="event.phoneLogo"
                  />
        </swiper-item>
      </swiper>
			 
      <view class="countdown-card">
        <view class="countdown-title"> 距离比赛开始还有 </view>
        <view class="countdown-values">
          <view class="countdown-item">
            <text class="num">{{ remain.days }}</text>
            <text class="label">DAYS</text>
          </view>
          <view class="divider"/>
          <view class="countdown-item">
            <text class="num">{{ remain.hours }}</text>
            <text class="label">Hours</text>
          </view>
          <view class="divider"/>
          <view class="countdown-item">
            <text class="num">{{ remain.minutes }}</text>
            <text class="label">Minutes</text>
          </view>
        </view>
      </view>
    </view>
	
	<view class="com-p-10">
		<!-- 快捷入口 -->
		<view class="quick-actions">
		  <view v-for="(item,index) in actions"
		        :key="item.text"
		        class="action"
		        @click="onAction(index)">
		    <image :src="item.icon" class="action-icon" mode="aspectFit" />
		    <text class="action-text">{{ item.text }}</text>
		  </view>
		</view>

    <!-- 公告模块 -->
		<view class="section notice-wrap">
		  <view class="section-title">
		    <text>公告通知</text>
		    <view class="more" @click="onMoreNotice">查看更多 ></view>
		  </view>
		  <view class="notice-list">
		    <view v-for="(item, index) in notice.slice(0, 3)" 
		          :key="item.id"
		          class="notice-item"
		          @click="onNoticeClick(item)">
		      <text class="notice-title">{{ item.title }}</text>
		    </view>
		  </view>
		</view>
		
		<!-- 参赛指南 -->
		<view class="section event-wrap">
		  <view class="section-title">
		    <text>参赛指南</text>
		    <view class="more" @click="onMoreGuide">查看更多 ></view>
		  </view>
		  <view class="com-flex">
		      <view class="com-flex-1 guide-item" v-for="(item, index) in events.slice(0, 3)" 
		          :key="item.id"
		          :style="{ marginRight: index < events.slice(0, 3).length - 1 ? '10rpx' : '0' }"
		            @click="openGuide(index + 1, item)">
		        <image class="guide-img"
		               :src="`../../static/images/index/guide${index + 1}.png`" />
		        <view class="guide-title" :style="{ color: eventColors[index] || '#333' }">{{ item.themeTitle }}</view>
			  </view>
		  </view>
		</view>
		
				<!-- 新闻模块 -->
		<view class="section news-section">
		  <view class="section-title">
		    <text>新闻资讯</text>
		    <view class="more" @click="onMoreNews">查看更多 ></view>
		  </view>
		  <swiper class="news-swiper" 
		          circular 
		          indicator-dots 
		          autoplay 
		          interval="4000"
		          indicator-color="rgba(255,255,255,0.3)"
		          indicator-active-color="#fff">
		    <swiper-item v-for="item in news" 
		                 :key="item.id"
		                 @click="onNewsClick(item)">
		      <view class="news-slide">
		        <image :src="item.image" 
		               class="news-slide-image" 
		               mode="aspectFill" />
		        <view class="news-slide-overlay">
		          <view class="news-slide-content">
		            <text class="news-slide-title">{{ item.title }}</text>
		            <view class="news-slide-meta">
		              <text class="news-slide-date">{{ formatDate(item.createDate) }}</text>
		            </view>
		          </view>
		        </view>
		      </view>
		    </swiper-item>
		  </swiper>
		</view>
		
		<!-- 精彩合集 -->
		<view class="section albums-section">
		  <view class="section-title">
		    <text>精彩合集</text>
		    <view class="more" @click="onMoreAlbums">查看更多 ></view>
		  </view>
		  <swiper class="albums-swiper" 
		          circular 
		          indicator-dots 
		          autoplay 
		          interval="5000"
		          indicator-color="rgba(255,255,255,0.3)"
		          indicator-active-color="#fff">
		    <swiper-item v-for="item in albums" 
		                 :key="item.id"
		                 @click="onAlbumClick(item)">
		      <view class="album-slide">
		        <image :src="item.image" 
		               class="album-slide-image" 
		               mode="aspectFill" />
		        <view class="album-slide-overlay">
		          <view class="album-slide-content">
		            <text class="album-slide-title">{{ item.name }}</text>
		            <view class="album-slide-meta">
		              <text class="album-slide-subtitle">精彩瞬间</text>
		            </view>
		          </view>
		        </view>
		      </view>
		    </swiper-item>
		  </swiper>
		</view>
		
		
	</view>
	</view>
	</view>

    
  </com-page>
</template>

<script>
export default {
  name: 'App-Index',
  data() {
    return {
      targetTime: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 22, 22, 42, 0).getTime(),
      remain: { days: '00', hours: '00', minutes: '00' },
      timer: null,
      actions: [
        { text: this.$t('pages_index_index_msg_12489261'), icon: '../../static/images/index/action1.png', key: 'register' },
        { text: this.$t('pages_index_index_msg_80f2bb5b'), icon: '../../static/images/index/action2.png', key: 'result' },
        { text: this.$t('pages_index_index_msg_bc2a50f0'), icon: '../../static/images/index/action3.png', key: 'register-query' },
        { text: this.$t('pages_index_index_msg_1df0987f'), icon: '../../static/images/index/action4.png', key: 'rules' },
      ],
      news: [],
      albums: [],
      notice: [],
      banners: [],
      events: [],
      eventList: [],
      currentEventId: null,
      currentEventName: '',
      beginTime: '',
      endTime: '',
	  eventColors: ['#60AC09','#1090FF','#FF8B29'],
    }
  },

  async onLoad() {
    try {
      // 首先获取赛事列表
      const eventListResult = await this.$api.event.list()
      this.eventList = eventListResult || []
      // 使用第一个赛事作为默认选中项
      if (this.eventList.length > 0) {
        this.currentEventId = this.eventList[0].id
        this.currentEventName = this.eventList[0].name
        // 将当前赛事ID存储到缓存
        uni.setStorageSync('currentEventId', this.currentEventId)
        await this.loadEventDetail(this.currentEventId)
      }
      
    } catch (error) {
      console.error('获取赛事列表失败:', error)
    }
	
    this.startCountdown()
    
    // 监听赛事切换事件
    uni.$on('switchEvent', this.handleSwitchEvent)
  },
  onUnload() {
    this.clearCountdown()
    // 移除事件监听
    uni.$off('switchEvent', this.handleSwitchEvent)
  },
  methods: {
    async loadEventDetail(eventId) {
      try {
        const result = await this.$api.event.getById(eventId)
        this.news = result['news'] || [];
        this.albums = result['albums'] || [];
        this.notice = result['contentPosts'] || [];
        this.banners = result['evt']['banners'] || [];
        this.events = result['evt']['contents'] || [];
        this.beginTime = result['evt']['beginTime'];
        this.endTime = result['evt']['endTime'];
        
        // 设置倒计时目标时间
        if (this.beginTime) {
          this.targetTime = new Date(this.beginTime).getTime()
          // 重新启动倒计时
          this.clearCountdown()
          this.startCountdown()
        }
        
        console.log('事件详情信息:', result)
      } catch (error) {
        console.error('获取事件详情失败:', error)
      }
    },
    onSwiperChange(e) {
      const currentIndex = e.detail.current
      if (this.eventList[currentIndex]) {
        const eventId = this.eventList[currentIndex].id
        this.currentEventId = eventId
        // 更新缓存中的当前赛事ID
        uni.setStorageSync('currentEventId', this.currentEventId)
        this.loadEventDetail(eventId)
      }
    },
    startCountdown() {
      this.updateRemain()
      this.timer = setInterval(this.updateRemain, 1000)
    },
    clearCountdown() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    updateRemain() {
      const now = Date.now()
      let diff = Math.max(0, this.targetTime - now)
      const dayMs = 24 * 60 * 60 * 1000
      const hourMs = 60 * 60 * 1000
      const minuteMs = 60 * 1000
      const days = Math.floor(diff / dayMs)
      diff -= days * dayMs
      const hours = Math.floor(diff / hourMs)
      diff -= hours * hourMs
      const minutes = Math.floor(diff / minuteMs)
      this.remain = {
        days: String(days).padStart(2, '0'),
        hours: String(hours).padStart(2, '0'),
        minutes: String(minutes).padStart(2, '0'),
      }
    },
    onAction(index) {
      const action = this.actions[index];
      
      if (index === 0) { // 比赛报名
        this.goToEventApply();
      } else if (index == 1) {
		  this.$utils.router({ url: '/pages/product/category/category' })
	  } else if (index === 2) { // 报名查询
        this.goToEventRecord();
      } else if (index === 3) { // 新闻咨询
        uni.navigateTo({
          url: `/pages/news/news?eventId=${this.currentEventId}`
        })
      } else {
        uni.showToast({ title: action.text, icon: 'none' });
      }
    },
    
    goToEventApply() {
      // 检查登录状态
      const token = uni.getStorageSync('token');
      if (!token) {
        // 未登录，跳转到登录页面
        uni.showModal({
          title: this.$t('pages_category_category_text_02d9819d'),
          content: this.$t('pages_index_index_desc_b61bfb74'),
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/account/login/login'
              })
            }
          }
        })
        return;
      }

      if (!this.events || this.events.length === 0) {
        uni.showToast({ title: this.$t('pages_index_index_msg_88e7f41b'), icon: 'none' });
        return;
      }
      
      // 将events数据存储到本地缓存
      uni.setStorageSync('tempEvents', this.events);
      uni.navigateTo({
        url: `/pages/event/apply/apply?evtId=${this.currentEventId}`
      });
    },

    goToEventRecord() {
      // 检查登录状态
      const token = uni.getStorageSync('token');
      if (!token) {
        // 未登录，跳转到登录页面
        uni.showModal({
          title: this.$t('pages_category_category_text_02d9819d'),
          content: this.$t('pages_index_index_desc_423f18cd'),
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/account/login/login'
              })
            }
          }
        })
        return;
      }

      // 跳转到报名记录页面
      uni.navigateTo({
        url: '/pages/user/event/event'
      });
    },
    onMoreGuide() {
      uni.navigateTo({
        url: `/pages/event/event?eventId=${this.currentEventId}&type=guide`
      })
    },
    openGuide(index, item) {
		
      if (item && item.themeContent) {
		  uni.setStorageSync('params',item)
        uni.navigateTo({
          url: `/pages/event/detail/detail?title=${item.themeTitle}`
        })
      } else {
        const map = { '1': this.$t('pages_index_index_msg_35956c98'), '2': this.$t('pages_index_index_msg_4d34c5f5'), '3': this.$t('pages_index_index_msg_6cb2853a') }
        uni.showToast({ title: `打开${map[index]}`, icon: 'none' })
      }
    },
    onMoreNews() {
      uni.navigateTo({
        url: `/pages/news/news?eventId=${this.currentEventId}`
      })
    },
    onNewsClick(item) {
		uni.setStorageSync('params',item)
      uni.navigateTo({
        url: `/pages/news/detail/detail`
      })
    },
    onMoreAlbums() {
      uni.navigateTo({
        url: `/pages/album/album?eventId=${this.currentEventId}`
      })
    },
    onAlbumClick(item) {
		uni.setStorageSync('params',item)
      uni.navigateTo({
        url: `/pages/album/detail/detail`
      })
    },
    onMoreNotice() {
      uni.navigateTo({
        url: `/pages/notice/notice?eventId=${this.currentEventId}`
      })
    },
    onNoticeClick(item) {
      uni.navigateTo({
        url: `/pages/notice/detail/detail`
      })
	  uni.setStorageSync('params',item)
    },
    formatDate(dateStr) {
      if (!dateStr) return this.$t('pages_album_album_msg_fbec222b')
      const date = new Date(dateStr)
      if (isNaN(date.getTime())) return this.$t('pages_album_album_msg_fbec222b')
      return `${date.getMonth() + 1}月${date.getDate()}日`
    },
    async handleSwitchEvent(data) {
      try {
        this.currentEventId = data.eventId
        this.currentEventName = data.eventName
        // 更新缓存中的当前赛事ID
        uni.setStorageSync('currentEventId', this.currentEventId)
        // 重新加载赛事详情数据
        await this.loadEventDetail(this.currentEventId)
        
        // 显示切换成功提示
        // uni.showToast({
        //   title: `已切换到${data.eventName}`,
        //   icon: 'success',
        //   duration: 1500
        // })
      } catch (error) {
        console.error('切换赛事失败:', error)
        // uni.showToast({
        //   title: '切换赛事失败',
        //   icon: 'error'
        // })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.home-page {
  // padding: 0 16rpx 32rpx;
}

.banner-wrapper {
  height: 420rpx;
  position: relative;
}

.banner-swiper {
  height: 420rpx;
  width: 100%;
}

.banner-image {
  height: 420rpx;
  width: 100%;
}
.countdown-card {
  position: absolute;
  left: 24rpx;
  right: 24rpx;
  bottom: -80rpx;
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 12rpx 24rpx rgba(0, 0, 0, 0.08);
  padding: 24rpx;
}
.countdown-title {
  text-align: center;
  color: #6b6b6b;
  font-size: 26rpx;
  margin-bottom: 12rpx;
}
.countdown-values {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.countdown-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.countdown-item .num {
  font-size: 48rpx;
  font-weight: 700;
  color: #5c5cff;
}
.countdown-item .label {
  margin-top: 6rpx;
  color: #999;
  font-size: 22rpx;
}
.divider {
  width: 2rpx;
  height: 60rpx;
  background: #eee;
}

.quick-actions {
  margin-top: 64rpx; /* 给倒计时卡片留位置 */
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16rpx;
}
.action {
  background: #fff;
  border-radius: 20rpx;
  padding: 24rpx 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.04);
}
.action-icon {
  width: 64rpx;
  height: 64rpx;
}
.action-text {
  margin-top: 12rpx;
  font-size: 24rpx;
  color: #333;
}

.section {
  margin-top: 28rpx;
}
.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8rpx 6rpx 20rpx 6rpx;
  font-size: 32rpx;
  font-weight: 600;
}
.more {
  color: #8a8a8a;
  font-size: 26rpx;
}

.guide-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  
  .guide-img {
    width: 100%;
    height: 160rpx;
    border-radius: 20rpx;
    overflow: hidden;
  }
  
  .guide-title {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
    font-size: 28rpx;
    color: #333;
    text-align: center;
    font-weight: 500;
  }
}

.event-wrap{
	padding: 24rpx;
	border-radius: 20rpx;
	background-image: url('@/static/images/index/event_bg.png');
	background-repeat: no-repeat;
	background-size: 100% 100%;
}

.news-section {
  margin-bottom: 40rpx;
}

.news-swiper {
  height: 320rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08);
}

.news-slide {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 20rpx;
  overflow: hidden;
}

.news-slide {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 20rpx;
  overflow: hidden;
}

.news-slide-image {
  width: 100%;
  height: 100%;
}

.news-slide-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 40rpx 24rpx 24rpx;
}

.news-slide-content {
  color: #fff;
}

.news-slide-title {
  font-size: 32rpx;
  font-weight: 700;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  margin-bottom: 16rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
}

.news-slide-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.news-slide-date {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
}

.news-slide-status {
  font-size: 22rpx;
  padding: 6rpx 16rpx;
  border-radius: 16rpx;
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  backdrop-filter: blur(10rpx);
}

.status-published {
  background: #e8f5e8;
  color: #52c41a;
}

.status-draft {
  background: #fff7e6;
  color: #fa8c16;
}

.status-offline {
  background: #f5f5f5;
  color: #999;
}

.status-unknown {
  background: #f0f0f0;
  color: #666;
}

.albums-section {
  margin-bottom: 40rpx;
}

.albums-swiper {
  height: 320rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08);
}

.album-slide {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 20rpx;
  overflow: hidden;
}

.album-slide {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 20rpx;
  overflow: hidden;
}

.album-slide-image {
  width: 100%;
  height: 100%;
}

.album-slide-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 40rpx 24rpx 24rpx;
}

.album-slide-content {
  color: #fff;
}

.album-slide-title {
  font-size: 32rpx;
  font-weight: 700;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  margin-bottom: 16rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
}

.album-slide-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.album-slide-subtitle {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
}

.album-slide-status {
  font-size: 22rpx;
  padding: 6rpx 16rpx;
  border-radius: 16rpx;
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  backdrop-filter: blur(10rpx);
}

.notice-wrap {
  padding: 24rpx;
  border-radius: 20rpx;
  background-image: url('@/static/images/index/event_bg.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  margin-bottom: 40rpx;
}

.notice-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.notice-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.notice-item:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.notice-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
}

</style>
